package com.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.controller.vo.ApplyVo;
import com.controller.vo.BankMetaVo;
import com.dao.IApplyDao;
import com.dao.ICustomerDao;
import com.dao.IRCustCommisDao;
import com.dao.entity.Apply;
import com.dao.entity.BankMeta;
import com.dao.entity.Customer;
import com.dao.entity.RCustCommis;
import com.service.IApplyService;
import com.service.IBankMetaService;
import com.utils.commons.PageUtils;
import com.utils.enums.ENUM_SUCESS;

@Service
public class ApplyServiceImpl implements IApplyService{
	
	@Autowired
	private IApplyDao applyDao;
	
	@Autowired
	private IBankMetaService bankMetaService;
	
	@Autowired
	private IRCustCommisDao rCustCommisDao;
	
	@Autowired
	private ICustomerDao customerDao;

	public Apply saveApply(Apply apply) {
		return applyDao.save(apply);
	}

	@Override
	public List<BankMetaVo> applySupport(Apply apply, Integer page, Integer size) {
		Optional<Customer> opt = customerDao.findById(apply.getCustomerId());
		opt.ifPresent(c ->{
			apply.setSex(c.getSex());
		});
		Page<BankMeta> pageResult = bankMetaService.applySupport(apply, page, size);
		List<BankMetaVo> result = new ArrayList<BankMetaVo>();
		pageResult.getContent().forEach(e -> {
			result.add(new BankMetaVo(e));
		});
		return result;
	}
	
	@Override
	public List<BankMetaVo> applySupport(Long applyId) {
		List<BankMetaVo> re = new ArrayList<BankMetaVo>();
		applyDao.findById(applyId).ifPresent(e ->{
			re.addAll(applySupport(e, 1, 100));
		});
		return re;
	}
	
	@Override
	public List<BankMetaVo> doApply(Apply apply, Integer page, Integer size){
		if(apply.getCustomerId() == null) {
			Customer c = customerDao.findByAccount(apply.getPhone());
			if(ObjectUtils.isEmpty(c)) {
				Customer entity = new Customer();
				entity.setAccount(apply.getPhone());
				entity.setIdCard(apply.getIdCard());
				entity.setSex(apply.getSex());
				entity.setUserName(apply.getUserName());
				entity.setPassword("111");
				entity = customerDao.save(entity);
				apply.setCustomerId(entity.getId());
			}
		}else {
			customerDao.findById(apply.getCustomerId()).ifPresent(e ->{
				apply.setPhone(e.getAccount());
				apply.setIdCard(e.getIdCard());
				apply.setSex(e.getSex());
				apply.setUserName(e.getUserName());
			});
		}
		//保存申请
		saveApply(apply);
		//保存客户-专员关联关系
		RCustCommis rcc = rCustCommisDao.findByCustomerIdAndCommisId(apply.getCustomerId(), apply.getCommisId());
		if(rcc == null) {
			rcc = new RCustCommis(apply.getCustomerId(), apply.getCommisId());
			rCustCommisDao.save(rcc);
		}
		
		return applySupport(apply, page, size);
	}

	@Override
	public Page<ApplyVo> getApplys(Apply apply, Integer page, Integer size){
		Pageable pageable = PageUtils.toPageable(page, size, Sort.Direction.ASC, "createdate");
		if(ObjectUtils.isEmpty(apply.getIsComplete())) {
			apply.setIsComplete(ENUM_SUCESS.NO.value);
		}
		Page<Apply> pageResult = findApply(apply, pageable);
		List<ApplyVo> temp = toPageVo(pageResult);
		return new PageImpl<ApplyVo>(temp, pageable, pageResult.getTotalElements());
	}
	
	@Override
	public void completeApply(Long applyId) {
		applyDao.findById(applyId).ifPresent(e ->{
			e.setIsComplete(ENUM_SUCESS.YES.value);
			applyDao.save(e);
			Long temp = applyDao.countByCustomerIdAndCommisIdAndIsComplete(e.getCustomerId(), e.getCommisId(), ENUM_SUCESS.NO.value);
			if(temp == 0) {
				RCustCommis r = rCustCommisDao.findByCustomerIdAndCommisId(e.getCustomerId(), e.getCommisId());
				rCustCommisDao.delete(r);
			}
		});
	}

	private Page<Apply> findApply(Apply apply, Pageable pageable){
		Map<String, Object> values = new HashMap<String, Object>();
		StringBuffer queryString = new StringBuffer("SELECT dc.id as id, dc.customerId as customerId, dc.age as age, dc.loanAge as loanAge, ")
				.append("dc.houseAge as houseAge, dc.landType as landType, dc.creditFile as creditFile, dc.otherFile as otherFile, ")
				.append("dc.isEconomize as isEconomize, dc.isComplete as isComplete, ")
				.append("dc.commisId as commisId, dc.isFeedback as isFeedback, dc.createdate as createdate, dc.updatedate as updatedate, dc.isdelete as isdelete\r\n")
				.append("FROM loan_apply dc\r\n")
				.append("where 1=1 ");
		if(!ObjectUtils.isEmpty(apply.getCustomerId())) {
			values.put("customerId", apply.getCustomerId());
			queryString.append(" and dc.customerId = :customerId\r\n");
		}
		if(!ObjectUtils.isEmpty(apply.getCommisId())) {
			values.put("commisId", apply.getCommisId());
			queryString.append(" and dc.commisId = :commisId\r\n");
		}
		if(!ObjectUtils.isEmpty(apply.getIsComplete())) {
			values.put("isComplete", apply.getIsComplete());
			queryString.append(" and dc.isComplete = :isComplete\r\n");
		}
		StringBuffer countString = new StringBuffer("select count(1) from (").append(queryString).append(") a");
		return applyDao.sqlQuery(queryString.toString(), countString.toString(), values, pageable);
	}

	private List<ApplyVo> toPageVo(Page<Apply> pageResult) {
		List<ApplyVo> temp = new ArrayList<ApplyVo>();
		pageResult.forEach(e ->{
			ApplyVo add = new ApplyVo(e);
			Customer cc = customerDao.findById(e.getCustomerId()).orElse(new Customer());
			add.setCustomerName(cc.getUserName());
			add.setSex(cc.getSex());
			temp.add(add);
		});
		return temp;
	}
}
